<template>
  <chart :options="options" :auto-resize="autoResize" :theme="theme" :watch-shallow="watchShallow"
      :class="className" :style="{height:height,width:width}"></chart>
</template>

<script>

export default {
  props: {
    title: { type: String, default: '' },
    chartData: { type: Object },
    className: { type: String, default: 'chart' },
    theme: { type: String, default: 'macarons' },
    autoResize: { type: Boolean, default: true },
    watchShallow: { type: Boolean, default: true },
    width: { type: String, default: '100%' },
    height: { type: String, default: '300px' }
  },
  data() {
    return {
      options: this.buildOptions(this.charData)
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.options = this.buildOptions(val)
      }
    }
  },
  mounted() {
    if (!this.options && this.chartData) {
      this.options = this.buildOptions(this.chartData)
    }
  },
  methods: {
    buildOptions(chartData) {
      // console.log(chartData)
      if (!chartData || !chartData.valueBeans) {
        return
      }
      var legendData = chartData.category

      var seriesData = chartData.valueBeans.map(item => {
        var seriesData = []
        for (var i = 0; i < legendData.length; i++) {
          seriesData.push({ name: legendData[i], value: item.data[i] })
        }
        return {
          name: item.name,
          type: 'pie',
          radius: ['40%', '80%'],
          center: ['50%', '50%'],
          label: {
            normal: {
              show: false,
              position: 'center'
            },
            emphasis: {
              show: false,
              textStyle: {
                fontSize: '30',
                fontWeight: 'bold'
              }
            }
          },
          labelLine: {
            normal: {
              show: false
            }
          },
          data: seriesData
        }
      })

      return {
        title: {
          text: this.title,
          x: 'center',
          y: 'center',
          textStyle: {
            fontSize: '25',
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: '2%',
          y: 'center',
          data: legendData
        },
        series: seriesData
      }
    }
  }
}
</script>
